package tr.edu.metu.is550.isell.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tr.edu.metu.is550.isell.domain.AlreadyExistsException;
import tr.edu.metu.is550.isell.domain.NotFoundException;
import tr.edu.metu.is550.isell.domain.User;
import tr.edu.metu.is550.isell.repository.UserRepository;

@Service
public class UserServiceImpl implements UserService {

    //TODO Remember ! CrudRepositories are transactional by default... We have to tweak UserRepository Interface

    @Autowired
    UserRepository repository;

    @Override
    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
    public boolean userExists(Long id) {
        return repository.exists(id);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public User addUser(User user) {
        User byUserCredentialsLoginName = repository.findByUserCredentialsLoginName(user.getUserCredentials().getLoginName());

        if (byUserCredentialsLoginName != null)
            throw new AlreadyExistsException("user", user.getUserCredentials().getLoginName());

        return repository.save(user);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public User updateUser(User user) {

        User userToBeUpdated = repository.findByUserCredentialsLoginName(user.getUserCredentials().getLoginName());

        if (userToBeUpdated == null)
            throw new NotFoundException("user", String.valueOf(user.getId()));

        userToBeUpdated.getUserCredentials().setPassword(user.getUserCredentials().getPassword());
        userToBeUpdated.getUserContactInfo().setAddress(user.getUserContactInfo().getAddress());
        userToBeUpdated.getUserContactInfo().setEmail(user.getUserContactInfo().getEmail());
        userToBeUpdated.getUserContactInfo().setName(user.getUserContactInfo().getName());
        userToBeUpdated.getUserContactInfo().setPhone(user.getUserContactInfo().getPhone());
        userToBeUpdated.getUserContactInfo().setSurname(user.getUserContactInfo().getSurname());

        return repository.save(userToBeUpdated);
    }

    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public User getUser(String loginName) {
        User user = repository.findByUserCredentialsLoginName(loginName);
        if (user == null)
            throw new NotFoundException("user", String.valueOf(loginName));

        return user;
    }
}
